package com.dycs.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.TypeReference;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author z1853
 */
public class JsonCollectionByJsonString {

    /**
     * 获取多个json字符串对象的交集
     * @param list json字符串集合
     * @return json交集字符串
     */
    public static String getIntersection(List<String> list) {
        if (list.size() != 0){
            List<Map<String,Object>> myList = new ArrayList<>();
            for (String str : list){
                Map<String,Object> map = transformToMap(str);
                if (map == null){
                    return null;
                }else {
                    myList.add(map);
                }
            }
            return JsonCollectionByJsons.jsonSplit(JsonCollectionByJsons.getIntersection(myList));
        }
        return "{}";
    }

    /**
     * json字符串转换成map集合
     * @param str json字符串
     * @return 存储key-value的map集合
     */
    public static Map<String,Object> transformToMap(String str) {
        if (JSON.isValid(str)){
            try{
                return JSON.parseObject(str,new TypeReference<Map<String,Object>>(){});
            }catch (JSONException e){
                return null;
            }
        }
        return null;
    }

}
